package com.heima.wemedia.service.impl;

import com.heima.feign.schedule.TaskFeignClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.schedule.dtos.Task;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private TaskFeignClient taskFeignClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        System.out.println("添加任务到延迟服务中----begin");
        Task task = new Task();
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setExecuteTime(publishTime.getTime());
        //序列化字节数组
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        byte[] serialize = ProtostuffUtil.serialize(wmNews);//使用谷歌序列化(效率高于jdk)
        task.setParameters(serialize);
        taskFeignClient.addTask(task);
        System.out.println("添加任务到延迟服务中----end");
    }

    /**
     * 消费延迟队列数据 (定时审核文章) <br><hr>
     * <h1>每1秒消费一次任务</h1>
     */
    @Override
    @Scheduled(cron = "0/1 * * * * ?")
    public void scanNewsByTask() {
        System.out.println("文章审核---消费任务执行---begin---");
        //1 拉取任务
        int taskType = TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();//任务类型
        int priority = TaskTypeEnum.NEWS_SCAN_TIME.getPriority();//任务优先级
        ResponseResult<Task> poll = taskFeignClient.poll(taskType, priority);
        //参数校验
        if (poll == null || poll.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            return;
        }
        //判断拉取的任务是否存在
        Task task = poll.getData();
        if (task == null) {
            return;
        }
        //2 审核文章
        //将任务对象的参数反序列化为wmNews对象,然后审核文章
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        System.out.println("文章审核---消费任务执行---end---");
    }
}
